const globalData = getApp().globalData;
import fetch from "../../utils/fetch";
import config from "../../utils/config";
Page({

  /**
   * 页面的初始数据
   */
  data: {
    deleteIndex: -1, //删除图片的序号
    number: 3, //剩余可选图片数量
    content: "", //动态内容
    imgs: [], //动态图片，最多三张
    sucImgs: [], //存放上传成功的图片
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {

  },
  //获取输入框的内容
  getValue: function (e) {
    this.setData({
      content: e.detail.value,
    });
  },
  // 上传图片
  chooseImgs() {
    const that = this;
    wx.chooseMedia({
      count: this.data.number,
      mediaType: ['image', 'video'],
      sourceType: ['album', 'camera'],
      maxDuration: 30,
      camera: 'back',
      success(res) {
        res.tempFiles.forEach(item => {
          that.data.imgs.push(item.tempFilePath);
          that.data.number--;
        })
        that.setData({
          imgs: that.data.imgs,
          number: that.data.number
        })
      }
    })
  },
  // 预览图片
  previewImg: function (e) {
    wx.previewImage({
      urls: this.data.imgs,
      current: this.data.imgs[e.currentTarget.dataset.id],
    })
  },
  deleteImg(e) {
    const id = e.currentTarget.dataset.id;
    this.setData({
      deleteIndex: id
    });
    this.data.imgs.splice(id, 1);
    this.data.number++;
    setTimeout(() => {
      this.setData({
        deleteIndex: -1,
        imgs: this.data.imgs,
        number: this.data.number
      })
    }, 500)
  },
  publish(e) {
    const content = this.data.content;
    const imgs = this.data.imgs;
    var that = this;
    //动态内容不能为空
    if (!content) {
      wx.showToast({
        title: '动态内容不能为空!',
        duration: 1000,
        icon: 'none'
      });
      return
    }
    wx.showLoading({
      title: '动态发布中',
    });
    // 检查文字是否安全
    fetch('/util/checkText', {
      content,
      openid: globalData.userInfo.openid,
      scene: 3
    }, 'post').then(res => {
      if (res.data.isLegal) {
        this.checkImgSafe(imgs).then(res=>{
          this.addArticle(content,that.data.sucImgs)
        }).catch(err=>{
          wx.hideLoading();
          if(err==0){
            wx.showToast({
              title: '上传图片不安全，已删除',
            })
          }else{
            wx.showToast({
              title: '图片上传失败',
            })
          }
        })
      }else{
        wx.showToast({
          title: '文字不安全',
        })
      }
    }).catch(err=>{
      this.publish()
    })
  },
  // 上传图片
  uploadImg(file, index) {
    var that = this;
    return new Promise((resolve, reject) => {
      wx.uploadFile({
        filePath: file,
        name: 'file',
        url: config.baseUrl + '/post/uploadImg',
        success(res) {
          const data = JSON.parse(res.data);
          const postImg = data.data.imageUrl;
          // 检查图片是否安全
          fetch('/util/checkImg', {
            openid: globalData.userInfo.openid,
            media_url: postImg
          }).then(res => {
            if (res.data.isLegal) {
              that.data.sucImgs.push(postImg);
              resolve(true);
            } else {
              that.data.imgs.splice(index, 1);
              that.setData({
                imgs: that.data.imgs,
                number: --that.data.number
              })
              reject(0)
            }
          })
        }
      })
    });
  },
  // 检查图片是否安全
  checkImgSafe(imgs) {
    let promiseArr = [];
    for (let i = 0; i < imgs.length; i++) {
      promiseArr.push(this.uploadImg(imgs[i], i))
    }
    if (imgs.length < 1) {
      return Promise.resolve();
    }
    return Promise.all(promiseArr);
  },
  addArticle(content,imgs){
    var that = this;
    //获取当前用户的id
    let userId = globalData.userInfo.id;
    fetch('/post/add',{
      content,
      imgs:imgs,
      userId:userId,
      place: globalData.userInfo.college
    },'post').then(res=>{
      globalData.userInfo.score +=1;
      wx.setStorageSync('userInfo', globalData.userInfo)
      const pages = getCurrentPages();
      const prepage = pages[pages.length - 2];
      prepage.setData({
        topPosition:0
      })
      wx.showToast({
        title: '发表成功',
      });
      setTimeout(()=>{
        wx.navigateBack()
      },1000);
    }).catch(err=>{
      this.addArticle(content,imgs);
    })
  }
})